package com.lin.realm;

import com.lin.entity.*;
import com.lin.service.*;
import com.lin.shiro.JWTToken;
import com.lin.utils.JWTUtil;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 霖霖
 * @version 1.0
 * @date 2023/3/29 11:25
 * @Description 用户
 */
@Component
public class UserRealm extends AuthorizingRealm {
    @Autowired
    private UcenterMemberService userService;

    public boolean supports(AuthenticationToken token) {
        return token instanceof JWTToken;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String userId =(String) principalCollection.getPrimaryPrincipal();
        List<AclRole> rolesEntity = userService.getRoles(userId);

        List<String> roles = rolesEntity.stream().map(AclRole::getRoleName).collect(Collectors.toList());
        List<String> roleIds = rolesEntity.stream().map(AclRole::getId).collect(Collectors.toList());
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.addRoles(roles);
        if (roleIds.size()==0)
            return simpleAuthorizationInfo;
        List<AclPermission> permissionsEntity = userService.getPermissions(roleIds);
        List<String> permissions = permissionsEntity.stream().map(AclPermission::getPermissionValue).collect(Collectors.toList());


        simpleAuthorizationInfo.addStringPermissions(permissions);
        return simpleAuthorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String token = (String) authenticationToken.getCredentials();
        if (!JWTUtil.checkToken(token))
            throw new AuthenticationException("token校验失败,请重新登录");
        String userId = JWTUtil.getTokenInfo(token);
        return new SimpleAuthenticationInfo(userId,token,this.getName());
    }
}
